<?php

declare (strict_types=1);

namespace app\common\listener;

use app\common\model\Business;
use app\common\model\BusinessCensus as BusinessCensusModel;
use think\facade\Db;

class BusinessCensus
{
    public function handle($data)
    {
        $method = $data['type'];
        $business = Business::where('id', $data['id'])
            ->field('id,type,sum_order_income,sum_order_count,not_recorded,recorded,draw')->find();
        $result = $this->$method($data, $business);
        if ($result !== true) {
            throw new \Exception($result);
        }
        return true;
    }

    /**
     * @param $data
     * @return bool|string
     * 原点 2023年1月11日15:17:14 统计相关
     */
    public function census($data, $business)
    {
        try {
            Db::transaction(function () use ($data, $business){
                $date = date("Y-m-d");
                if($info = BusinessCensusModel::where(['create_date' => $date, 'business_id' => $business->id])->find()){
                    $info->order_income = $info->order_income + $data['total'];
                    $info->order_count = $info->order_count + 1;
                    $info->save();
                }else{
                    BusinessCensusModel::create([
                        'business_id'  => $business->id,
                        'year'         => date("Y"),
                        'month'        => date("m"),
                        'day'          => date("d"),
                        'create_date'  => date("Y-m-d"),
                        'order_income' => $data['total'],
                        'order_count'  => 1,
                    ]);
                }
                $business->sum_order_income = $business->sum_order_income + $data['total'];
                $business->sum_order_count = $business->sum_order_count + 1;
                $business->not_recorded = $business->not_recorded + $data['total'];
                $business->save();
            });
            return true;
        } catch (\Exception $e) {
            return $e->getMessage();
        }
    }

    /**
     * @param $data
     * @param $business
     * @return bool|string
     * 原点 2023年1月11日15:18:34 入账未入账
     */
    public function recorded($data, $business)
    {
        try {
            $business->draw = $business->draw + $data['total'];
            $business->recorded = $business->recorded + $data['total'];
            $business->not_recorded = $business->not_recorded - $data['total'];
            $business->save();
            return true;
        } catch (\Exception $e) {
            return $e->getMessage();
        }
    }

}